//
//  SettingView.swift
//  YXRSmartDeviceDemo
//
//  Created by run on 2024/7/1.
//

import Foundation
import SwiftUI

struct SettingView: View {
    

    @State var macAddress: String = Server.testMac
    @State var lockKey: String =  Server.testLockkey
    @State var featureCode: String = Server.testFeatureCode
    @State var trackId: String = Server.testTrackId != nil ? "\(Server.testTrackId!)": ""

    var body: some View {
        VStack(alignment: .center) {
            Spacer().frame(height: 40)
            YxrInputView("Mac地址：", text: $macAddress)
            YxrInputView("秘钥：", text: $lockKey)
            
            YxrInputView("FeatureCode", placeholderText: "可为空", text: $featureCode)
            YxrInputView("TrackId", placeholderText: "留空用默认", text: $trackId)
                .keyboardType(.numberPad)
            
            YxrConfirmView(action: onTapConfirm).padding(.top, 30)
            
            Spacer()
            Text("system: \(UIDevice.current.systemVersion)").font(.system(size: 14.0))
            if let versionNumber = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String,
               let buildNumber = Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as? String {
                Text("App Version: \(versionNumber)").font(.system(size: 14.0))
                Text("buildNumber: \(buildNumber)").font(.system(size: 14.0))
            }
            
        }
        .padding(.zero)
        .onTapGesture {
            endEditing(true)
        }
        .yxrNavigationTitle("设置")
            .onAppear {
                macAddress = Server.testMac
                lockKey =  Server.testLockkey
                featureCode = Server.testFeatureCode
                trackId = Server.testTrackId != nil ? "\(Server.testTrackId!)": ""
            }
    }

    private func endEditing(_ force: Bool) {
        MainApp.keyWindow?.endEditing(force)
    }

    func onTapConfirm() {
        print("mac：\(macAddress), lockKey：\(lockKey)")

        if macAddress.count != 17 {
            showToast("macAddress不符合格式")
            return
        }
        
        if lockKey.count != 32 {
            showToast("秘钥不符合格式")
            return
        }
        
        let tId = trackId.isEmpty ? nil: UInt32(trackId)
        
        Server.testMac = macAddress
        Server.testLockkey = lockKey
        Server.testFeatureCode = featureCode
        Server.testTrackId = tId
        
        showToast("保存成功")
    }
}

